/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.controller;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.result.R;
import org.springframework.web.bind.annotation.*;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.Participants;
import top.continew.admin.hanfu.domain.dto.ParticipantsDto;
import top.continew.admin.hanfu.service.impl.OssFileServiceImpl;
import top.continew.admin.hanfu.service.impl.ParticipantsServiceImpl;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-03-31
 */
@RestController
@RequestMapping("/participants")
@RequiredArgsConstructor
public class ParticipantsController {

    private final ParticipantsServiceImpl participantsService;

    private final OssFileServiceImpl ossFileService;

    private final OSS oss;

    @PostMapping("")
    public R addParticipants(@RequestBody ParticipantsDto participantsDto) {

        Participants participants = BeanUtil.copyProperties(participantsDto, Participants.class);

        participants.setUpdateTime(System.currentTimeMillis() + "");

        boolean save = participantsService.save(participants);

        return save ? R.success(participants.getId()) : R.fail("新增失败");
    }

    @DeleteMapping("/{id}")
    public R delParticipants(@PathVariable("id") Integer id) {

        Participants byId = participantsService.getById(id);

        oss.deleteFile(Integer.parseInt(byId.getParticipantsAvatar()));

        boolean b = participantsService.removeById(id);

        return b ? R.success() : R.fail("删除失败");
    }

    @GetMapping("/active/{id}")
    public R getParticipantsByActiveId(@PathVariable("id") Integer id) {

        List<Participants> list = participantsService.lambdaQuery().eq(Participants::getActiveId, id).list();

        List<ParticipantsDto> participantsDtos = BeanUtil.copyToList(list, ParticipantsDto.class);

        participantsDtos.forEach(i -> {

            OssFile byId = ossFileService.getById(i.getParticipantsAvatar());

            i.setClientUrl(byId.getClientUrl());

        });

        return R.success(participantsDtos);
    }

}
